﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Antlr.Runtime;
using Antlr.Runtime.Tree;

namespace XYZCompiler
{
    public partial class SyntacticResult : Form
    {
        public BaseTree result;



        public SyntacticResult(object result)
        {
            this.result = result as BaseTree;
            if (this.result == null)
            {
                MessageBox.Show(StringRes.ResultDialogInputError);
                DialogResult = DialogResult.Abort;
            }
            InitializeComponent();

            this.DialogResult = DialogResult.Abort;
        }

        private void SyntacticResult_Load(object sender, EventArgs e)
        {
            treeView1.Nodes.Add("Root");
            var tree = result;
            curNode = this.treeView1.Nodes[0];
            visit(tree);
            MessageBox.Show("The weight of tree is : "+countWeight(result).ToString());
        }

        private TreeNode curNode = null;

        private void visit(ITree t)
        {
            TreeNode pre = curNode;
            curNode = curNode.Nodes.Add(t.Text);
            for (int i = 0; i < t.ChildCount; i++)
                visit(t.GetChild(i));
            curNode = pre;

        }
        private int countWeight(ITree t)
        {
            int count=0;
            ITree c;
            for(int i =0;i<t.ChildCount;i++)
            {
                c = t.GetChild(i);
                if (c.Text == "<=" )
                    count++;
                else if (c.Text == "return")
                    count++;
                else if (c.Text == "if")
                    count += (countWeight(c.GetChild(1))+countWeight(c.GetChild(2)))*2;
                else if (c.Text == "while")
                {
                    for (int ii = 1; ii < c.ChildCount; ii++)
                        count += countWeight(c.GetChild(ii)) * 2;
                }
                //if (c.Text == "VARDECL")
                //  count++;
                else
                    count += countWeight(c);
            }
            return count;
        }
    }
}
